package com.stoneframe.plugin.webSocketOnline;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.java_websocket.WebSocket;


/**
 * 在线管理
 */
public class OnlineChatServerPool {
	
	private static final Map<WebSocket,String> userConn=new HashMap<WebSocket,String>();
	
	/**
	 * 获取用户名
	 */
	public static String getUserByKey(WebSocket conn){
		return userConn.get(conn);
	}
	
	/**
	 * 获取在线总数
	 */
	public static int getUserCount(){
		return userConn.size();
	}
	
	/**
	 * 获取WebSocket
	 */
	public static WebSocket getWebSocketByUser(String user){
		Set<WebSocket> keySet = userConn.keySet();
		synchronized (keySet) {
			for (WebSocket conn : keySet) {
				String cuser = userConn.get(conn);
				if(cuser.equals(user)){
					return conn;
				}
			}
		}
		return null;
	}
	
	/**
	 * 向连接池中添加连接
	 */
	public static void addUser(String user, WebSocket conn){
		userConn.put(conn,user);	//添加连接
	}
	
	/**
	 * 获取所有的在线用户
	 */
	public static Collection<String> getOnlineUser(){
		List<String> setUsers = new ArrayList<String>();
		Collection<String> setUser = userConn.values();
		for(String u:setUser){
			setUsers.add(u);
		}
		return setUsers;
	}
	
	/**
	 * 移除连接池中的连接
	 */
	public static boolean removeUser(WebSocket conn){
		if(userConn.containsKey(conn)){
			userConn.remove(conn);	//移除连接
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 向特定的用户发送数据
	 */
	public static void sendMessage(WebSocket conn,String message){
		if(null != conn){
			conn.send(message);
		}
	}
	
	/**
	 * 向所有的用户发送消息
	 */
	public static void sendMessage(String message){
		Set<WebSocket> keySet = userConn.keySet();
		synchronized (keySet) {
			for (WebSocket conn : keySet) {
				String user = userConn.get(conn);
				if(user != null){
					conn.send(message);
				}
			}
		}
	}

}
